﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Api.Common
{
    public class ConvertHelper
    {
        /// <summary>
        /// 泛型實現任何數據之前的轉化
        /// </summary>
        /// <typeparam name="T">目標類型</typeparam>
        /// <typeparam name="T2">原數據類型</typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T GetValue<T, T2>(T2 value)
        {
            IConvertible obj = value as IConvertible;
            if (obj != null && !string.IsNullOrEmpty(value.ToString()))
            {
                Type type = typeof(T);
                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.Empty:
                        break;
                    case TypeCode.Object:
                        return (T)obj;
                    case TypeCode.Boolean:
                        return (T)(object)obj.ToBoolean(null);
                    case TypeCode.Char:
                        return (T)(object)obj.ToChar(null);
                    case TypeCode.SByte:
                        return (T)(object)obj.ToSByte(null);
                    case TypeCode.Byte:
                        return (T)(object)obj.ToByte(null);
                    case TypeCode.Int16:
                        return (T)(object)obj.ToInt16(null);
                    case TypeCode.UInt16:
                        return (T)(object)obj.ToUInt16(null);
                    case TypeCode.Int32:
                        return (T)(object)obj.ToInt32(null);
                    case TypeCode.UInt32:
                        return (T)(object)obj.ToUInt32(null);
                    case TypeCode.Int64:
                        return (T)(object)obj.ToInt64(null);
                    case TypeCode.UInt64:
                        return (T)(object)obj.ToUInt64(null);
                    case TypeCode.Single:
                        return (T)(object)obj.ToSingle(null);
                    case TypeCode.Double:
                        return (T)(object)obj.ToDouble(null);
                    case TypeCode.Decimal:
                        return (T)(object)obj.ToDecimal(null);
                    case TypeCode.DateTime:
                        return (T)(object)obj.ToDateTime(null);
                    case TypeCode.String:
                        return (T)(object)obj.ToString(null);
                }
            }
            return default(T);
        }
    }
}
